# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions


# This is a simple example for a custom action which utters "Hello World!"

from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

import sys
import redis
from redisgraph import Graph

try:
    r = redis.Redis("172.17.0.1", "6379")
    redis_g = Graph("tcm", r)
except Exception as e:
    sys.exit(-1)

#
#
# class ActionHelloWorld(Action):
#
#     def name(self) -> Text:
#         return "action_hello_world"
#
#     def run(self, dispatcher: CollectingDispatcher,
#             tracker: Tracker,
#             domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
#
#         dispatcher.utter_message(text="Hello World!")
#
#         return []

class ActionSearchSyndrome(Action):
    def name(self) -> Text:
        return "action_search_syndrome"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        try:
            dispatcher.utter_message()
            ps = {
                "syndrome": next(tracker.get_latest_entity_values("syndrome"))
            }
            q = """MATCH (temp:Term {name:$syndrome})<-[]-(result)
            RETURN result.name"""
            result = redis_g.query(q, params=ps, timeout=30)
            records = []
            for record in result.result_set:
                record_temp = str(record[0])
                if record_temp != "None":
                    records.append(record_temp)
            if len(records) != 0:
                dispatcher.utter_message(text=ps['syndrome'] + "有" + "、".join(records) + "等记录！")
            else:
                dispatcher.utter_message("知识库中暂无与 {0} 相关的记录".format(ps['syndrome']))
        except Exception as e:
            dispatcher.utter_message(str(e.__traceback__.tb_lineno) + ": " + str(e))
        return []